#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(slotSendData()));

    serialPort = new QSerialPort(this);
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        serialPort->setPort(info);
        if(serialPort->open(QIODevice::ReadWrite))
        {
            ui->comboBoxCom->addItem(info.portName());
            ui->textEditInfo->append(QStringLiteral("检测到端口列表"));
            ui->textEditInfo->append(info.portName());
            ui->textEditInfo->append(info.description());
            ui->textEditInfo->append(info.manufacturer());
            serialPort->close();
        }
    }

    connect(serialPort,SIGNAL(readyRead()),this,SLOT(slotReadData()));
    ui->comboBoxBaudRate->setCurrentIndex(0);
    ui->pushButtonStart->setEnabled(false);
    ui->pushButtonStop->setEnabled(false);
    ui->pushButtonCloseCom->setEnabled(false);


}

Widget::~Widget()
{
    delete ui;
    if(timer->isActive())
    {
        timer->stop();
    }
}

void Widget::slotSendData()
{
    QByteArray temp;
    temp.append(getCurrentTime());
    temp.append("#");
    serialPort->write(temp);
}
void Widget::slotReadData()
{
    QByteArray temp = serialPort->readAll();

    if(!temp.isEmpty())
    {
        byteArray.append(temp);
        if(byteArray.contains("#"))
        {
            ui->textEditReceive->setText(byteArray.split('#').at(0));
            byteArray = byteArray.right(byteArray.length()-byteArray.indexOf('#')-1);
        }
    }
}

void Widget::on_pushButtonStart_clicked()
{
    timer->start(0);//能发多快就发多快
}
void Widget::on_pushButtonStop_clicked()
{
    if(timer->isActive())
    {
        timer->stop();
    }
}
void Widget::on_pushButtonOpenCom_clicked()
{
    serialPort->setPortName(ui->comboBoxCom->currentText());
    serialPort->open(QIODevice::ReadWrite);
    serialPort->setBaudRate(ui->comboBoxBaudRate->currentText().toInt());
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);

    ui->pushButtonOpenCom->setEnabled(false);
    ui->pushButtonCloseCom->setEnabled(true);
    ui->pushButtonStart->setEnabled(true);
    ui->pushButtonStop->setEnabled(true);

}
void Widget::on_pushButtonCloseCom_clicked()
{
    if(serialPort->isOpen())
    {
        serialPort->close();
        ui->pushButtonOpenCom->setEnabled(true);
        ui->pushButtonCloseCom->setEnabled(false);
        ui->pushButtonStart->setEnabled(false);
        ui->pushButtonStop->setEnabled(false);
    }
}

QString Widget::getCurrentTime()
{
    QDateTime dateTime = QDateTime::currentDateTime();
    return dateTime.toString("hh-mm-ss-zzz");
}
